<template>
  <div id="content">
    <globle-linear-border>
      <el-card class="searchBox">
        <el-form :inline="true">
          <el-form-item label="姓名">
            <el-input v-model="pageQuery.otherParams.stuName" placeholder="输入姓名关键字" clearable @blur="getPageInfo" @clear="getPageInfo" />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="pageQuery.otherParams.stuSex" placeholder="选择学生性别" clearable @change="getPageInfo">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="专业">
            <el-input v-model="pageQuery.otherParams.major" placeholder="输入专业关键字" clearable @blur="getPageInfo" @clear="getPageInfo" />
          </el-form-item>
          <el-form-item label="学院">
            <el-input v-model="pageQuery.otherParams.college" placeholder="输入学院关键字" clearable @blur="getPageInfo" @clear="getPageInfo" />
          </el-form-item>
          <el-form-item label="选拔考试">
            <el-select v-model="pageQuery.otherParams.isExam" placeholder="选择学生是否参加选拔考" clearable @change="getPageInfo">
              <el-option label="已参加" value="1" />
              <el-option label="未参加" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否被删除">
            <el-select v-model="pageQuery.otherParams.isDelete" placeholder="选择是否被删除搜索" clearable @change="getPageInfo">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
        </el-form>
        <section>
          <el-button type="success" icon="Plus" @click="onAdd">添加学生</el-button>
          <el-button type="danger" icon="Minus" @click="onBatchDelete">批量删除</el-button>
          <el-upload :action="uploadUrl" :show-file-list="false" :on-progress="onProgress" :on-success="onSuccess" accept=".xlsx" :limit="1">
            <el-button type="warning" icon="Download">导入数据</el-button>
          </el-upload>
          <el-button type="warning" icon="Upload" @click="onExpose">导出数据</el-button>
        </section>
      </el-card>
    </globle-linear-border>

    <globle-linear-border style="margin-top: 20px">
      <el-card class="mainBox">
        <span v-if="tableData.rows">
          <el-table
            :border="true"
            stripe
            ref="tableRef"
            :data="tableData.rows"
            @selection-change="onSeleceChange"
            cell-class-name="table-cell"
            header-cell-class-name="table-header-cell"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column property="studentId" label="学号" width="160" show-overflow-tooltip />
            <el-table-column property="name" label="姓名" width="100" />
            <el-table-column label="性别">
              <template #default="scope">{{ scope.row.sex === 1 ? '男' : '女' }}</template>
            </el-table-column>
            <el-table-column property="major" label="专业" width="100">
              <template #default="scope">
                <span>{{ blank(scope.row.major) }}</span>
              </template>
            </el-table-column>
            <el-table-column property="college" label="学院" width="180">
              <template #default="scope">
                <span>{{ blank(scope.row.college) }}</span>
              </template>
            </el-table-column>
            <el-table-column property="phone" label="手机号" width="140" />
            <el-table-column property="qq" label="QQ号" width="140">
              <template #default="scope">
                <span>{{ blank(scope.row.qq) }}</span>
              </template>
            </el-table-column>
            <el-table-column property="identityId" label="身份证号" width="220">
              <template #default="scope">
                <span>{{ blank(scope.row.identityId) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="选拔考试" width="120">
              <template #default="scope">
                <el-tag effect="dark" type="success" v-if="scope.row.isExam === 1">已参加</el-tag>
                <el-tag effect="dark" type="danger" v-else>未参加</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
              <template #default="scope">
                <el-button type="primary" size="small" icon="Edit" @click="onEdit(scope.row)">修改</el-button>
                <el-button v-if="scope.row.isDelete === 0" type="danger" size="small" icon="Delete" @click="onDelete(scope.row)">删除</el-button>
                <el-button v-else type="warning" size="small" icon="RefreshRight" @click="onDelete(scope.row)">恢复</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-model:currentPage="pageQuery.pageParams.pageNum"
            v-model:page-size="pageQuery.pageParams.pageSize"
            :page-sizes="pageSizeOption"
            :background="true"
            :small="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.totalSize"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
          />
        </span>
      </el-card>
    </globle-linear-border>
    <!-- 弹窗 -->
    <suspense>
      <dialog-vue ref="dialogRef" @onReGetData="getPageInfo"></dialog-vue>
    </suspense>
  </div>
</template>

<script lang="ts" setup>
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElTable, UploadFile } from 'element-plus';
import { IPageRes, APIData, IRecruitment, IRecruitmentParams } from '../../../type';
import { useUserStore } from '../../../store/user';
import { useAPI } from '../../../request/api';
import { useUtils } from '../../../utils';
//注意!!定义动态引入组件时需要使用defineAsyncComponent，并且在template中需要搭配suspense组件使用,它是一个异步组件解决方案。
const DialogVue = defineAsyncComponent(() => import('./Dialog.vue'));
const store = useUserStore();

onMounted(() => {
  getPageInfo();
});

const blank = computed(() => (str: string) => {
  if (str === null || str === '') return '无';
  else return str;
});

const api = useAPI();
const utils = useUtils();
const dialogRef = ref();
const tableRef = ref<InstanceType<typeof ElTable>>();
const uploadUrl = `${api.baseUrl}/teacher/fileImport/recruitment`;

let falseDeleteStuList = [] as Array<string>;
const pageSizeOption = [5, 10, 15, 20];
const pageQuery = reactive<IRecruitmentParams>({
  otherParams: {
    college: '',
    isExam: '',
    major: '',
    stuName: '',
    stuSex: '',
    isDelete: '',
  },
  pageParams: {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: '',
  },
});
const tableData = ref({} as IPageRes);

const onEdit = (row: IRecruitment) => {
  dialogRef.value.openDialogByEdit(row);
};
// const onDelete = (deleteId: string) => {
//   utils.openDeleteMsgBox(() => {
//     falseDeleteStuList.push(deleteId);
//     falseDeleteStu();
//   });
// };
const onDelete = (row: IRecruitment) => {
  if (row.isDelete === 0) {
    utils.openDeleteMsgBox(() => {
      falseDeleteStuList.push(row.id);
      falseDeleteStu();
    });
  } else if (row.isDelete === 1) {
    row.isDelete = 0;
    postModify(row, '恢复成功');
  }
};
const onAdd = () => {
  dialogRef.value.openDialogByAdd();
};

const postModify = async (row: IRecruitment, message: string) => {
  const res: APIData = await api.save(row, store.role, 'recruitment');
  if (res.code === 200) ElMessage.success(message);
  else ElMessage.error(res.message);
};

//上传进行
const onProgress = (evt: any, uploadFile: UploadFile) => {
  ElMessage.warning(`${uploadFile.name}正在上传中`);
};
//上传成功
const onSuccess = (response: APIData, uploadFile: UploadFile) => {
  if (response.code === 200) {
    getPageInfo();
    ElMessage.success(`${uploadFile.name}上传成功`);
  } else ElMessage.error(`${uploadFile.name}上传失败,请重试`);
};

//导出
const onExpose = () => {
  window.open(`${api.baseUrl}/teacher/fileExport/recruitment`, '_self');
};

//分页大小
const onSizeChange = (val: number) => {
  pageQuery.pageParams.pageSize = val;
  getPageInfo();
};
//分页页码
const onCurrentChange = (val: number) => {
  pageQuery.pageParams.pageNum = val;
  getPageInfo();
};

//勾选(仅收集删除数据)
const onSeleceChange = (rowList: IRecruitment[]) => {
  falseDeleteStuList = [] as Array<string>;
  rowList.forEach(item => {
    falseDeleteStuList.push(item.id);
  });
};
//勾选删除
const onBatchDelete = () => {
  if (falseDeleteStuList.length !== 0)
    utils.openDeleteMsgBox(() => {
      falseDeleteStu();
    });
  else ElMessage.error('未勾选任何数据');
};

const getPageInfo = async () => {
  const res: APIData = await api.findPage(pageQuery, store.role, 'recruitment');
  if (res.code === 200) tableData.value = res.data;
  else ElMessage.error(res.message);
};
const falseDeleteStu = async () => {
  const res = await api.falseDelete(falseDeleteStuList, store.role, 'recruitment');
  if (res.data) {
    ElMessage.success('删除成功');
    getPageInfo();
  }
};
</script>

<style lang="scss" scoped>
#content {
  height: 100%;
  .searchBox {
    &-item {
      margin-right: 10px;
    }
    :deep(.el-form-item) {
      margin-bottom: 8px;
    }
    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
    }
    section {
      display: flex;
    }
    :deep(.el-input__wrapper) {
      width: 200px;
    }
  }
  :deep(.el-checkbox__inner) {
    background-color: var(--main-color);
    transition: background 0.3s ease;
  }
  :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: var(--active-color);
    transition: background 0.3s ease;
  }
}
</style>
